"""Codex审查工作流的文件生成器。"""

from pathlib import Path

# Import encoding detector
try:
    from .encoding_utils import EncodingDetector
except ImportError:
    from encoding_utils import EncodingDetector

# Import Codex review templates
try:
    from .template import CODEX_REVIEWER_TEMPLATE, REPORT_FORMAT_TEMPLATE
except ImportError:
    from template import CODEX_REVIEWER_TEMPLATE, REPORT_FORMAT_TEMPLATE


class FileGenerator:
    """为Codex审查生成所有必需的文件。"""

    def __init__(self, session_dir: Path) -> None:
        """初始化文件生成器。

        Args:
            session_dir: 会话目录路径
        """
        self.session_dir = Path(session_dir)

    def _expand_placeholders(self, text: str) -> str:
        """替换文本中的占位符为完整的Codex审查规则。

        占位符系统：
        - {{INJECT:CODEX_INSTRUCTIONS}} → 完整的六步工作流和七维质量标准
        - {{INJECT:REPORT_FORMAT}} → 完整的report.md格式规范

        这使ClaudeCode能够生成轻量级文件（~2k tokens），
        而Codex获得完整规则（~15-20k tokens）。

        Args:
            text: 包含占位符的原始文本

        Returns:
            替换占位符后的文本
        """
        text = text.replace('{{INJECT:CODEX_INSTRUCTIONS}}', CODEX_REVIEWER_TEMPLATE)
        text = text.replace('{{INJECT:REPORT_FORMAT}}', REPORT_FORMAT_TEMPLATE)
        return text

    def copy_files_to_session(
        self,
        review_request_path: str,
        draft_path: str
    ) -> tuple[Path, Path]:
        """将ClaudeCode临时文件复制到会话目录，统一使用UTF-8编码。

        工作流程：
        1. 智能读取临时文件（尝试UTF-8/UTF-8-BOM/GBK/GB18030）
        2. 替换review-request.md中的占位符（注入完整Codex规则）
        3. 写入会话目录（统一使用UTF-8无BOM）
        4. 删除临时文件

        Args:
            review_request_path: review_request.md临时文件的绝对路径
            draft_path: draft.md临时文件的绝对路径

        Returns:
            (review_file, draft_file): 会话目录中的文件路径

        Raises:
            FileNotFoundError: 临时文件未找到
            UnicodeDecodeError: 文件编码无法检测
        """
        # Smart read from temp files (support multiple encodings including BOM)
        review_text = EncodingDetector.read_file(Path(review_request_path), support_bom=True)
        draft_text = EncodingDetector.read_file(Path(draft_path), support_bom=True)

        # Expand placeholders in review-request.md (inject full Codex rules)
        review_text = self._expand_placeholders(review_text)

        # Write to session directory (unified UTF-8 without BOM)
        review_file = self.session_dir / "review-request.md"
        draft_file = self.session_dir / "draft.md"
        review_file.write_text(review_text, encoding='utf-8')  # Changed: utf-8-sig → utf-8
        draft_file.write_text(draft_text, encoding='utf-8')

        # Delete temp files (use missing_ok to avoid exception)
        Path(review_request_path).unlink(missing_ok=True)
        Path(draft_path).unlink(missing_ok=True)

        return review_file, draft_file
